<template>
  <vueJsonEditor
    v-model="jsonData"
    :show-btns="false"
    :mode="'code'"
    lang="zh"
    @json-change="onJsonChange"
    @json-save="onJsonSave"
    @has-error="onError"
  ></vueJsonEditor>

</template>

<script>
import vueJsonEditor from 'vue-json-editor';

export default {
  components: {vueJsonEditor},
  props: {
    content: Object | String
  },
  data() {
    return {
      jsonStr: this.content,
      hasJsonFlag:true,  // json是否验证通过
    }
  },
  watch:{
    content(newVal) {
      this.jsonStr = newVal;
    }
  },
  computed:{
    jsonData:{
      get() {
        if(!this.jsonStr) return {};

        if(typeof this.jsonStr == 'string') {
          return JSON.parse(this.jsonStr);
        } else {
          return this.jsonStr;
        }
      },

      set(val) {
        this.jsonStr = val;
      }
    },

  },
  methods: {
    onJsonChange (value) {
       // console.log('更改value:', value);
      // 实时保存
      this.onJsonSave(value);
    },
    onJsonSave (value) {
      // console.log('保存value:', value);

      this.jsonData = value;
      this.hasJsonFlag = true;

      this.$emit("changeValue", value);
    },
    onError(value) {
      // console.log("json错误了value:", value);
      this.hasJsonFlag = false
    },

    // 检查json
    checkJson(){
      if (this.hasJsonFlag == false){
        // console.log("json验证失败")
        // this.$message.error("json验证失败")
        alert("json验证失败")
        return false
      } else {
        // console.log("json验证成功")
        // this.$message.success("json验证成功")
        alert("json验证成功")
        return true
      }
    },
  }
}
</script>

<style scoped>


/deep/ .jsoneditor-poweredBy {
  display: none !important;
}

/deep/ .jsoneditor-separator {
  display: none !important;
}

/*/deep/ .json-save-btn {*/
/*  display: none !important;*/
/*}*/

</style>
